package grpc_module

import (
	"context"
	"gitee.com/kmyss/gf-ex/ysgrpc"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
)

func newWatchModule() *watchModule {
	return &watchModule{}
}

type watchModule struct {
	ysgrpc.MQBaseModule
	param *gmap.StrAnyMap

	Topics string
}

func (m *watchModule) setParam(param *gmap.StrAnyMap) {
	m.param = param

	_ = gconv.Struct(param.MapStrAny(), m)
	//m.Topics = m.param.GetVar("Topics").String()
}

func (m *watchModule) Init(ctx context.Context) {
	cfg := ysgrpc.NewDefaultMQModuleCfg()
	cfg.Name = "watch"
	cfg.UseUnPack = false
	cfg.HasSubAllTopic = g.IsEmpty(m.Topics)

	m.SetCfg(cfg)
	m.MQBaseModule.Init(ctx)

	if !g.IsEmpty(m.Topics) {
		for _, t := range gstr.SplitAndTrim(m.Topics, ",") {
			m.AddTopic(t)
		}
	}

	m.AddHandlerFunc("", m.watch)
}
func (m *watchModule) watch(topic string, msg []byte) {
	l := len(msg)
	if l > 1024 {
		l = 1024
	}
	m.Log().Infof(m.Ctx(), "\n 话题: %s\n 消息: %s", topic, msg[:l])
}
